package com.eduhzy.ttw.teacher.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ResourceUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.HomeListData;
import com.eduhzy.ttw.commonsdk.entity.HomeSection;
import com.eduhzy.ttw.commonsdk.entity.LatestMsg;
import com.eduhzy.ttw.commonsdk.imgaEngine.GlideImageLoader;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.eduhzy.ttw.teacher.R;
import com.eduhzy.ttw.teacher.di.component.DaggerHomeComponent;
import com.eduhzy.ttw.teacher.mvp.contract.HomeContract;
import com.eduhzy.ttw.teacher.mvp.presenter.HomePresenter;
import com.eduhzy.ttw.teacher.mvp.ui.adapter.HomeMultiAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.youth.banner.Banner;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.simple.eventbus.Subscriber;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;
import static com.eduhzy.ttw.commonsdk.core.Constants.HOME_ITEM_TYPE.ITEM_HEAD;
import static com.eduhzy.ttw.commonsdk.core.Constants.HOME_ITEM_TYPE.ITEM_HOME;
import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-7-20 8:37:20
 */
@Route(path = RouterHub.APP_HOMEFRAGMENT)
public class HomeFragment extends BaseFragment<HomePresenter> implements HomeContract.View {
    private static final int REQUEST_CODE_SCAN = 11;
    //    int[] imgs = new int[]{R.drawable.but_zuoye,R.drawable.but_zuoye, R.drawable.but_zhiboketang, R.drawable.but_more, R.drawable.but_kejianbofang, R.drawable.but_ketangpingjia, R.drawable.but_tiwendayi, R.drawable.but_kong};
    int[] imgs = new int[]{R.drawable.but_zhiboketang, R.drawable.but_zuoye, R.drawable.but_kejianbofang, R.drawable.but_ketangpingjia, R.drawable.but_huodongpingbi};
    String[] names = {"直播课程", "作业", "课件播放", "课堂表现", "活动评比",};
    String[] routers = {
            RouterHub.COURSELIVE_COURSELIVEMAINACTIVITY,
            RouterHub.WORK_WORKHOMEACTIVITY,
            RouterHub.RXFEATURE_ACTIVITYSCANERCODE,
            RouterHub.CLAZZ_HOMEACTIVITY,
            RouterHub.RATING_RATINGHOMEACTIVITY,
    };
    @Inject
    List<HomeSection<HomeListData>> lists;
    @Inject
    HomeMultiAdapter mAdapter;
    @Inject
    GridLayoutManager mManager;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;
    private List<HomeSection<HomeListData>> hideLists;
    private View header;
    private Banner banner;
    private HomeSection<HomeListData> vermsg;
    private HomeSection<HomeListData> sysmsg;
    private HomeListData data1;
    private HomeListData data;

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        rvList.getItemAnimator().setChangeDuration(0);
        mSwipeLayout.setOnRefreshListener(() -> {
            getDatas();
        });
        mAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                if (lists.get(position).isHeader()) {
                    return 1;
                } else {
                    return gridLayoutManager.getSpanCount();
                }
            }
        });
        mAdapter.setOnShowMoreChangeListener(new HomeMultiAdapter.OnShowMoreChangeListener() {
            @Override
            public void onShowMoreChange(boolean isShowMore, int position) {
                if (isShowMore) {
                    lists.remove(position);
                    lists.addAll(position, hideLists);
                    mAdapter.notifyDataSetChanged();
                } else {

                }
            }
        });
        rvList.setLayoutManager(mManager);
        rvList.setAdapter(mAdapter);
        addOrRefreshHeaderView();
        rvList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view) - mAdapter.getHeaderLayoutCount();
                if (position - 1 >= 0) {
                    HomeListData section = mAdapter.getData().get(position).getT();
                    HomeListData pre = mAdapter.getData().get(position - 1).getT();
                    if (section != null && pre != null && !section.isHead() && pre.isHead()) {
                        outRect.set(0, RxUtil.getAutoHeight(getActivity(), 30), 0, 0);
                    } else {
                        super.getItemOffsets(outRect, view, parent, state);
                    }
                }
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                HomeSection<HomeListData> section = lists.get(position);
                if (section.isHeader() && section.getImg() == R.drawable.but_more) {
                    mAdapter.setShowMore(true, position);
                    return;
                }
                HomeListData t = section.getT();
                if (!section.isHeader() && t != null && t.isHead()) {
                    if (ObjectUtils.isNotEmpty(t.getRouter())) {
                        if (t.getRouter().equals(RouterHub.APP_VERIFYMESSAGEACTIVITY)) {
                            if (ObjectUtils.isNotEmpty(vermsg) && ObjectUtils.isNotEmpty(vermsg.getT())) {
                                vermsg.getT().setCount(0);
                                mAdapter.notifyDataSetChanged();
                            }
                        } else if (t.getRouter().equals(RouterHub.APP_PLATFORMNOTICEACTIVITY)) {
                            if (ObjectUtils.isNotEmpty(sysmsg) && ObjectUtils.isNotEmpty(sysmsg.getT())) {
                                sysmsg.getT().setCount(0);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                        Utils.navigation(t.getRouter());
                    }
                    return;
                }
                if (ObjectUtils.isNotEmpty(section.getRouter())) {
                    if (section.getRouter().equals(RouterHub.RXFEATURE_ACTIVITYSCANERCODE)) {
                        Intent intent = new Intent(getActivity(), CaptureActivity.class);
                        ZxingConfig config = new ZxingConfig();
                        config.setPlayBeep(true);//是否播放扫描声音 默认为true
                        config.setShake(true);//是否震动  默认为true
                        config.setDecodeBarCode(false);//是否扫描条形码 默认为true
                        config.setReactColor(R.color.white);//设置扫描框四个角的颜色 默认为淡蓝色
                        config.setFrameLineColor(R.color.white);//设置扫描框边框颜色 默认无色
                        config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                        intent.putExtra(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, config);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    } else {
                        Utils.navigationWithTitle(getActivity(), section.getRouter(), section.getName());
                    }
                } else {
                    showMessage("你点到我了");
                }
            }
        });
        getDatas();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            String code = data.getStringExtra(Constant.CODED_CONTENT);
            ARouter.getInstance().build(RouterHub.APP_WEBVIEWACTIVITY)
                    .withString(Intent.EXTRA_TITLE, "详情")
                    .withString(Constants.ROUTER_STRING, code)
                    .navigation();
        }
    }

    @Subscriber(tag = RouterHub.APP_HOMEFRAGMENT)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.SCANER_CODE_SUCCESS:
                String code = (String) msg.obj;
                ARouter.getInstance().build(RouterHub.APP_WEBVIEWACTIVITY)
                        .withString(Intent.EXTRA_TITLE, "详情")
                        .withString(Constants.ROUTER_STRING, code)
                        .navigation();
                break;
            case EventBusTags.UPDATE_JPUSH_APPLY_CLASS:
//                if (ObjectUtils.isEmpty(vermsg)) {
//                    vermsg = new HomeSection<>(new HomeListData());
//                }
//                JPushData jPushData = (JPushData) msg.obj;
//                HomeListData homeListData = vermsg.getT();
//                homeListData.setCount(homeListData.getCount() + 1);
//                homeListData.setDate(TimeUtils.millis2String(jPushData.getDate(), new SimpleDateFormat("HH:mm")));
//                homeListData.setTitle(jPushData.getTitle());
//                homeListData.setDesc(jPushData.getBody());
//                mAdapter.notifyItemChanged(lists.indexOf(vermsg));
                getDatas();
                break;
            default:
        }
    }

    private void getDatas() {
        mPresenter.getLateMsg();
        showLoading();
//        lists.clear();
        if (hideLists == null) hideLists = new ArrayList<>();
        hideLists.clear();
        Observable.create((ObservableOnSubscribe<HomeSection>) emitter -> {
            if (lists.size() >= names.length) {
                emitter.onComplete();
                return;
            }
            for (int i = 0; i < names.length; i++) {
                HomeSection homeSection = new HomeSection(true, imgs[i], names[i]);
                if (routers.length > i) {
                    homeSection.setRouter(routers[i]);
                }
                homeSection.setItemType(ITEM_HEAD);
                lists.add(homeSection);
//                if (i < 4) {
//                } else {
//                    hideLists.add(homeSection);
//                }
            }

            initSystemMsg();
            initVerifyMsg();
            emitter.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<HomeSection>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(HomeSection url) {
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                mAdapter.notifyDataSetChanged();
                hideLoading();
            }
        });
    }

    private void initVerifyMsg() {
        if (ObjectUtils.isEmpty(vermsg)) {
            data1 = new HomeListData("验证消息", "暂无消息", "", true);
            data1.setRouter(RouterHub.APP_VERIFYMESSAGEACTIVITY);
            data1.setResId(R.drawable.img_tongguo);
            vermsg = new HomeSection(data1).setMessageType(HomeSection.VERMSG).setItemType(ITEM_HOME);
        }
        if (!lists.contains(vermsg)) {
            lists.add(ObjectUtils.isEmpty(vermsg) ? names.length : names.length + 1, vermsg);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void initSystemMsg() {
        if (ObjectUtils.isEmpty(sysmsg)) {
            data = new HomeListData("系统通知", "暂无通知", "", true);
            data.setRouter(RouterHub.APP_PLATFORMNOTICEACTIVITY);
            data.setResId(R.drawable.img_xiaoxi);
            sysmsg = new HomeSection(data).setMessageType(HomeSection.SYSMSG).setItemType(ITEM_HOME);
        }
        if (!lists.contains(sysmsg)) {
            lists.add(names.length, sysmsg);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void addOrRefreshHeaderView() {
        List<String> imgs = new ArrayList<>();
        File file1 = new File(getActivity().getExternalCacheDir(), "img_banner1.png");
        ResourceUtils.copyFileFromAssets("img_banner1.png", file1.getPath());
        File file2 = new File(getActivity().getExternalCacheDir(), "img_banner2.png");
        ResourceUtils.copyFileFromAssets("img_banner2.png", file2.getPath());
        imgs.add(file2.getPath());
        imgs.add(file1.getPath());
        if (header == null) {
            header = getLayoutInflater().inflate(R.layout.rating_banner_head, null);
            this.banner = header.findViewById(R.id.banner);
            mAdapter.addHeaderView(header);
        }
        this.banner.setImages(imgs)
                .setImageLoader(new GlideImageLoader())
                .setOnBannerListener(position -> {
                            ARouter.getInstance().build(RouterHub.COURSELIVE_COURSEDETAILSACTIVITY)
                                    .withInt(Constants.ROUTER_INTEGER, 1027 + position)
                                    .withString(Intent.EXTRA_TITLE, Constants.COURSE_DETAILS)
                                    .withString(Constants.ROUTER_IMG, imgs.get(position))
                                    .navigation();
                        }
                )
                .start();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        mSwipeLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        mSwipeLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_INFO, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void updateMsg(LatestMsg latestMsg) {
        if (ObjectUtils.isNotEmpty(latestMsg)) {

            if (ObjectUtils.isNotEmpty(sysmsg) && ObjectUtils.isNotEmpty(latestMsg.getSystemMsg())) {
                sysmsg.getT().setCount(latestMsg.getUnreadSystemMsgCount());
                sysmsg.getT().setDesc(latestMsg.getSystemMsg().getContent());
                mAdapter.notifyDataSetChanged();
            }

            if (ObjectUtils.isNotEmpty(vermsg) && ObjectUtils.isNotEmpty(latestMsg.getValidateMsg())) {
                vermsg.getT().setCount(latestMsg.getUnreadValidateMsgCount());
                vermsg.getT().setDesc(latestMsg.getValidateMsg().getContent());
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}
